package com.itheima;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.client.*;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.swing.*;

public class MongoDriverDemo2 {

    private MongoCollection<Document> collection = null;
    MongoClient mongoClient = null;

    @Before
    public void init() {
        mongoClient = MongoClients.create("mongodb://127.0.0.1:27017");
        //2.通过MongClient对象获取数据库
        MongoDatabase database = mongoClient.getDatabase("test");

        //3.通过集合（表）获取文档
        collection = database.getCollection("user");
    }




    @After
    public void close() {
        mongoClient.close();
    }


    @Test
    public void insert() {
        Document document = new Document();
        document.put("username", "zhangsan");
        document.put("age", 20);
        collection.insertOne(document);
    }

    @Test
    public void testByAge(){

        BasicDBObject queryCondition = new BasicDBObject();


        BasicDBObject basicDBObject = new BasicDBObject();
        BasicDBObject basicDBObject1 = new BasicDBObject("age", new BasicDBObject("$lte", 23));
        BasicDBObject basicDBObject2 = new BasicDBObject("age", new BasicDBObject("$gte", 1));


        BasicDBList values = new BasicDBList();
        values.add(basicDBObject1);
        values.add(basicDBObject2);
        queryCondition.put("$and", values);

        FindIterable<Document> documents = collection.find(queryCondition);
        for (Document document : documents) {
            System.out.println(document.toString());
        }
    }

    @Test
    public void update() {
        BasicDBObject query = new BasicDBObject("id", 3.0);
        UpdateResult updateResult = collection.updateOne(query, Updates.set("age", 12));
        System.out.println(updateResult);
    }

    @Test
    public void delete() {
        BasicDBObject query = new BasicDBObject("id", 3.0);
        DeleteResult deleteResult = collection.deleteOne(query);
        System.out.println(deleteResult);
    }
}
